<template>
  <div class="app-container">
    <el-drawer
      title="FQC检验详情"
      :visible.sync="visible"
      size="90%"
      :before-close="cancel"
      custom-class="demo-drawer"
      :append-to-body="true"
    >
      <div style="padding: 20px;padding-top:0px">
        <div style="margin-left: 20px;">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出
          </el-button>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- <el-row>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="form.productName" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工单编码" prop="projectCode">
                <el-input v-model="form.projectCode" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报检数量" prop="quantityDeclared">
                <el-input v-model="form.quantityDeclared" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="检验类型" prop="fqcInspectionType">
                <el-select v-model="form.fqcInspectionType" placeholder="请选择检验类型">
                  <el-option label="全检" value="0"></el-option>
                  <el-option label="抽检" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.fqcInspectionType == '1'">
              <el-form-item label="抽样数量" prop="sampleNumber">
                <el-input-number
                  :controls="false"
                  v-model="form.sampleNumber"
                  :disabled="optType=='add'? false:true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格数量" prop="qualifiedCode">
                <el-input
                  v-model="form.qualifiedCode"
                  placeholder
                  :disabled="optType=='add'? false:true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量" prop="unqualifiedCode">
                <el-input
                  v-model="form.unqualifiedCode"
                  placeholder
                  :disabled="optType=='add'? false:true"
                />
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row>
            <el-col :span="8">
              <el-form-item label="产品编码" prop="productCode">
                <el-input v-model="form.productCode" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="form.productName" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品规格" prop="productSpec">
                <el-input v-model="form.productSpec" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="客户" prop="clientName">
                <el-input v-model="form.clientName" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同号" prop="ftext4">
                <el-input v-model="form.ftext4" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="技术分解号" prop="ftext1">
                <el-input v-model="form.ftext1" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报检数量" prop="quantityDeclared">
                <el-input v-model="form.quantityDeclared" placeholder :disabled="true"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="检验类型" prop="fqcInspectionType">
                <el-select
                  v-model="form.fqcInspectionType"
                  placeholder="请选择检验类型"
                  :disabled="true"
                >
                  <el-option label="全检" value="0"></el-option>
                  <el-option label="抽检" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.fqcInspectionType == '1'">
              <el-form-item label="抽样数量" prop="sampleNumber">
                <el-input-number
                  :controls="false"
                  v-model="form.sampleNumber"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格数量" prop="qualifiedCode">
                <el-input
                  v-model="form.qualifiedCode"
                  placeholder
                  :disabled="true"
                  @change="(value)=>autoInput(value,'qualifiedCode','unqualifiedCode')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量" prop="unqualifiedCode">
                <el-input
                  v-model="form.unqualifiedCode"
                  placeholder
                  :disabled="true"
                  @change="(value)=>autoInput(value,'unqualifiedCode','qualifiedCode')"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="SN码">
                <div>
                  <el-checkbox-group v-model="snList">
                    <el-checkbox v-for="item in snCodeAllList" :label="item" :key="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <el-table-column label="类型" align="center" prop="indexType" width="160px">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_index_type" :value="scope.row.indexType"/>
                </template>
              </el-table-column>
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="检测项目" align="center" prop="indexName" width="260px"/>

              <el-table-column align="center" prop="checkResult" width="240px" label="检查结果">
                <template slot-scope="scope">
                  <div>
                    <div
                      style="font-size:20px"
                    >{{ scope.row.checkResult == '0' ? "×" : scope.row.checkResult == '1' ? "√" : "--" }}
                    </div>
                    <div v-if="scope.row.attrObj.type=='2'">
                      <div class="mInput">
                        <span>标准值</span>
                        <span>{{ scope.row.attrObj.standard }}：</span>
                        <span>{{ scope.row.attrObj.num }}</span>
                      </div>
                    </div>
                    <ul v-if="scope.row.attrObj.type=='4'">
                      <li class="mInput">
                        <span>长</span>
                        <span>{{ scope.row.attrObj.lStandard }},</span>
                        <span>{{ scope.row.attrObj.lNum }}</span>
                      </li>
                      <li class="mInput">
                        <span>宽</span>
                        <span>{{ scope.row.attrObj.wStandard }},</span>
                        <span>{{ scope.row.attrObj.wNum }}</span>
                      </li>
                      <li class="mInput">
                        <span>高</span>
                        <span>{{ scope.row.attrObj.hStandard }},</span>
                        <span>{{ scope.row.attrObj.hNum }}</span>
                      </li>
                    </ul>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <el-col :span="24" class="imgDiv">
              <el-form-item label="检验结果" prop="checkResult">
                <el-radio-group v-model="form.checkResult">
                  <el-radio :label="1">√</el-radio>
                  <el-radio :label="0">×</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-table-column label="异常描述" align="center" prop="describeData">
              <template slot-scope="scope">
                <el-input v-model="scope.row.describeData" placeholder type="textarea"/>
              </template>
            </el-table-column>
            <!-- :disabled="form.state =='0'?false:true" -->
            <el-col :span="16">
              <el-form-item label="备注:" prop="remark">
                <!--                <el-input-->
                <!--                  v-model="form.remark"-->
                <!--                  type="textarea"-->
                <!--                  placeholder="输入备注"-->
                <!--                  style="width: 450px; height: 50px"-->
                <!--                ></el-input>-->
                <template slot-scope="scope">
                  <el-input v-model="form.remark" placeholder="输入备注" type="textarea"/>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 不合格品异常记录列表 -->
          <div v-if="form.checkResult ==0">
            <el-form-item label="不合格品处理方式" prop="repairState">
              <span>
                ：
                {{ form.repairState == '1' ? '返工' : form.repairState == '2' ? "返修" : "--" }}
              </span>
            </el-form-item>

            <el-form-item label="异常记录">
              <el-table :data="exceptionLogList">
                <el-table-column label="类型选择" align="center" prop="indexType">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexType" placeholder="请选择检测项类型" clearable>
                      <el-option
                        v-for="dict in errorTypeList"
                        :key="dict.indexType"
                        :label="dict.indexTypeName"
                        :value="dict.indexTypeName"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="异常描述" align="center" prop="describeData">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.describeData" placeholder type="textarea"/>
                  </template>
                </el-table-column>
                <el-table-column label="文件上传" align="center" prop="fileName">
                  <template slot-scope="scope">
                    <ImageUpload
                      :limit="1"
                      :value="scope.row.fileName"
                      :fileSize="15"
                      @input="(url)=>handleImgUplaoded(url,scope.$index)"
                      @onRemoved="(url)=>handleImgRemoved(url,scope.$index)"
                    ></ImageUpload>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="medium"
                      type="text"
                      icon="el-icon-circle-plus-outline"
                      @click="errorAdd(item)"
                    ></el-button>
                    <el-button
                      v-if="scope.$index != 0"
                      size="medium"
                      type="text"
                      icon="el-icon-remove-outline"
                      @click="errorDel(scope.$index)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {getFqcDtoInfo, exportFqcInfo} from "@/api/mes/qc/fqc";
import {tansParams, blobValidate} from "@/utils/hici";
import {Message, Loading} from "element-ui";
import {saveAs} from "file-saver";

let downloadLoadingInstance;
export default {
  name: "replenishment",

  dicts: ["mes_index_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      visible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      form: {},
      optType: "view",
      // 弹出层标题

      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      // 模板列表
      templateList: [],
      loading1: false,
      spanArr: [],
      // 异常记录列表
      exceptionLogList: [{}],
      // 不合格数
      failedSncode: [],
      // 首页列表信息
      QcFqcAcInspectionHead: {},
      errorTypeList: [],
      snCodeAllList: [],
      snList: [],
      rules: {
        snCode: [{required: true, message: "SN码不能为空", trigger: "blur"}],
        unqualifiedCode: [
          {required: true, message: "不合格数量不能为空", trigger: "blur"}
        ],
        qualifiedCode: [
          {required: true, message: "合格数量不能为空", trigger: "blur"}
        ],
        checkResult: [
          {required: true, message: "检验结果不能为空", trigger: "change"}
        ],

        headEndCheckType: [
          {required: true, message: "类型不能为空", trigger: "change"}
        ]
      },
      formDetail: {},
    };
  },
  created() {
    // this.getList();
  },

  methods: {
    init(row) {
      this.visible = true;
      this.getList(row);
    },
    /** 查询产品制程物料BOM列表 */
    getList(row) {
      this.QcFqcAcInspectionHead = row;
      getFqcDtoInfo(row).then(res => {
        console.log(res, "[]========res=====");
        let list = [];
        this.formDetail = {...res.data}
        this.form = {
          ...res.data.qcInspectionResult,
          ...res.data.qcFqcAcInspectionHead,

        };
        this.form.remark = res.data.qcFqcAcInspectionHead.remark;
        // list = res.data[0].itemList;
        console.log(this.templateList, "=======itemList====");
        for (let i = 0; i < res.data.itemList.length; i++) {
          let obj = res.data.itemList[i];
          let attrList = res.data.itemList[i].attr2;
          obj.resultList = JSON.parse(attrList);
          obj.attrObj = obj.attr1 ? JSON.parse(obj.attr1) : {type: "0"};
          if (obj.attrObj.type == "2") {
            let attr2 = res.data.itemList[i].attr2
              ? JSON.parse(res.data.itemList[i].attr2)
              : {};
            obj.attrObj.num = attr2.num;
          }
          if (obj.attrObj.type == "4") {
            let attr2 = res.data.itemList[i].attr2
              ? JSON.parse(res.data.itemList[i].attr2)
              : {};
            obj.attrObj.lNum = attr2.lNum;
            obj.attrObj.wNum = attr2.wNum;
            obj.attrObj.hNum = attr2.hNum;
          }

          list.push(obj);
        }
        this.exceptionLogList = res.data?.qcInspectionResult.exceptionLogList;
        console.log(list, "=======list=====");
        this.templateList = list || [];
        this.snCodeAllList = this.snList = res.data.snCodeList || [];
        // this.open = true;
        this.title = "查看检验详情";
        this.optType = "view";
        this.getSpanArr(list || []);
      });
    },
    cancel() {
      this.formDetail = {}
      this.visible = false;
      this.routeproductbomList = [];
    },
    // 行合并
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].indexType === data[i - 1].indexType) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      let query = {...this.formDetail};
      downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      exportFqcInfo(query)
        .then(async data => {
          console.log(query, "======");
          const isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data]);
            saveAs(blob, `FQC检验详情.xlsx`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            Message.error(errMsg);
          }
          downloadLoadingInstance.close();
        })
        .catch(r => {
          console.error(r);
          Message.error("下载文件出现错误，请联系管理员！");
          downloadLoadingInstance.close();
        });
      // this.downloadDetail(
      //   "mes/qc/iqc/export/iqcInfo",
      //   {
      //     ...this.form
      //   },
      //   `iqcDetail_${new Date().getTime()}.xlsx`
      // );
    }
  }
};
</script>
